﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Order : System.Web.UI.Page
{
    RestaurantBooking.OrdersDataTable orders;
    RestaurantBookingTableAdapters.OrdersTableAdapter adapter;
    DataView dv;
    RestaurantBooking.DishesDataTable dishesDataTable = null;
    RestaurantBookingTableAdapters.DishesTableAdapter dishesAdapter = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        orders = new RestaurantBooking.OrdersDataTable();
        adapter = new RestaurantBookingTableAdapters.OrdersTableAdapter();
        adapter.Fill(orders);
        dv = orders.DefaultView;

        DatePicker1.SelectedDate = DateTime.Now;
        DatePicker1.MinValidDate = DateTime.Now;

        if (!IsPostBack)
        {
            dataBind();
        }
        
    }

    protected void dataBind()
    {
        if (Session["Authentication"] != null)
        {
            if (Session["Authentication"].ToString().Equals("Member"))
            {
                memberOnly();
            }
            else
            {
                adminOnly();
            }
        }
    }

    protected void memberOnly()
    {
        MemberOnly.Visible = true;
        dv.RowFilter = "CustomerID = " + Session["UserID"].ToString();

        PagedDataSource pgitems = new PagedDataSource();
        pgitems.DataSource = dv;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 5;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptPrevOrdersPages.Visible = true;
            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptPrevOrdersPages.DataSource = pages;
            rptPrevOrdersPages.DataBind();
        }
        else
            rptPrevOrdersPages.Visible = false;
        rptPrevOrders.DataSource = pgitems;
        rptPrevOrders.DataBind();

    }

    protected void adminOnly()
    {
        OrderTable.Visible = false;
        AdminOnly.Visible = true;
        
        PagedDataSource pgitems = new PagedDataSource();
        pgitems.DataSource = dv;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 5;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptOrderPages.Visible = true;
            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptOrderPages.DataSource = pages;
            rptOrderPages.DataBind();
        }
        else
            rptOrderPages.Visible = false;
        rptOrders.DataSource = pgitems;
        rptOrders.DataBind();

    }

    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            RestaurantBooking.OrdersRow newOrder = orders.NewOrdersRow();
            newOrder.CustomerID = Int32.Parse(Session["UserID"].ToString());
            newOrder.Quantity = Int16.Parse(txtNumberofTables.Text);
            newOrder.Note = txtNote.Text;
            newOrder.Status = "Waiting";

            DateTime selectedDate = DatePicker1.SelectedDate;
            DateTime orderDate = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, Int32.Parse(ddlHour.Text), Int32.Parse(ddlMinute.Text), 0);
            newOrder.Order_Time = orderDate;

            RestaurantBooking.DishesDataTable menuTable = (RestaurantBooking.DishesDataTable)Session["Menu"];
            String menu = "";
            Int32 price = 0;
            dishesDataTable = new RestaurantBooking.DishesDataTable();
            dishesAdapter = new RestaurantBookingTableAdapters.DishesTableAdapter();

            dishesAdapter.Fill(dishesDataTable);

            foreach (RestaurantBooking.DishesRow dish in menuTable)
            {
                if (dish.RowState == DataRowState.Deleted)
                {
                    continue;
                }
                if (!menu.Equals(""))
                {
                    menu += ",";
                }
                foreach (RestaurantBooking.DishesRow d in dishesDataTable)
                {
                    if (d.Name == dish.Name)
                    {
                        menu += d.ID;
                    }
                }
                
                price += dish.Price;
            }
            newOrder.Menu = menu;
            newOrder.Price = price * newOrder.Quantity;

            orders.Rows.Add(newOrder);
            adapter.Update(orders);

            //lblMessage.Text = "The Order is sent .";
            //lblMessage.Visible = true;

            Response.Redirect("~/Redirecting.aspx?Destination=" + this.Request.Url.LocalPath.ToString());
        }
    }
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (Session["Authentication"] == null)
        {
            args.IsValid = false;
        }
    }
    protected void rptPrevOrders_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblID = (Label)e.Item.FindControl("lblID");
            Label lblMenu = (Label)e.Item.FindControl("lblMenu");
            Label lblPrice = (Label)e.Item.FindControl("lblPrice");
            Label lblOrderDate = (Label)e.Item.FindControl("lblOrderDate");
            Label lblOrderTime = (Label)e.Item.FindControl("lblOrderTime");

            

            dv.Sort = "ID";
            String ID = dv.FindRows(lblID.Text)[0].Row["ID"].ToString();
            RestaurantBooking.OrdersRow order = orders.FindByID(Int32.Parse(ID));
            

            lblMenu.Text = getDishesNameFromDishesID(order.Menu);
            lblPrice.Text = (order.Price / order.Quantity).ToString();
            lblOrderDate.Text = order.Order_Time.ToString("MM/dd/yyy");
            lblOrderTime.Text = order.Order_Time.ToString("hh:mm");
        }

        
    }
    protected String getDishesNameFromDishesID(String ID)
    {
        RestaurantBooking.DishesDataTable dishes = new RestaurantBooking.DishesDataTable();
        RestaurantBookingTableAdapters.DishesTableAdapter apt = new RestaurantBookingTableAdapters.DishesTableAdapter();
        apt.Fill(dishes);
        DataView dishView = dishes.DefaultView;
        String name = "";

        dishView.RowFilter = "ID in (" + ID + ")";

        foreach (DataRowView dish in dishView)
        {
            if (!name.Equals(""))
            {
                name += ",";
            }
            name += dish["Name"];
        }

        return name;
    }

    protected void rptPages_ItemCommand(object source,RepeaterCommandEventArgs e)
    {
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
        dataBind();
    }

    public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;
        }
    }


    protected void ddlOrderStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        String filter = ddlOrderStatus.SelectedValue;
        if (filter.Equals("All"))
        {
            dv.RowFilter = "";
        }
        else
        {
            dv.RowFilter = "Status = '" + filter + "'";
        }
        
        adminOnly();
    }
    protected void ChangeOrderStatus(object sender, CommandEventArgs e)
    {
        int ID = Int32.Parse(e.CommandArgument.ToString());
        RestaurantBooking.OrdersRow orderRow = orders.FindByID(ID);
        orderRow.Status = e.CommandName;
        adapter.Update(orderRow);
        adminOnly();
    }

    protected void rptOrders_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblID = (Label)e.Item.FindControl("lblID");
            Label lblCustomerName = (Label)e.Item.FindControl("lblCustomerName");
            Label lblMenu = (Label)e.Item.FindControl("lblMenu");
            Label lblPrice = (Label)e.Item.FindControl("lblPrice");
            Label lblOrderDate = (Label)e.Item.FindControl("lblOrderDate");
            Label lblOrderTime = (Label)e.Item.FindControl("lblOrderTime");
            Label lblStatus = (Label)e.Item.FindControl("lblStatus");
            Button btnAccept=(Button)e.Item.FindControl("btnAccept");
            Button btnRefuse=(Button)e.Item.FindControl("btnRefuse");

            dv.Sort = "ID";
            String ID = dv.FindRows(lblID.Text)[0].Row["ID"].ToString();
            RestaurantBooking.OrdersRow order = orders.FindByID(Int32.Parse(ID));

            RestaurantBooking.UsersDataTable user = new RestaurantBooking.UsersDataTable();
            RestaurantBookingTableAdapters.UsersTableAdapter a = new RestaurantBookingTableAdapters.UsersTableAdapter();
            a.Fill(user);

            lblCustomerName.Text=user.FindByID(order.CustomerID).Name;
            lblMenu.Text = getDishesNameFromDishesID(order.Menu);
            lblPrice.Text = (order.Price / order.Quantity).ToString();
            lblOrderDate.Text = order.Order_Time.ToString("MM/dd/yyy");
            lblOrderTime.Text = order.Order_Time.ToString("hh:mm");
            lblStatus.Text=order.Status;

            if (order.Status.Equals("Waiting"))
            {
                lblStatus.Visible = false;
                btnRefuse.Visible = true;
                btnAccept.Visible = true;
            }
            else
            {
                lblStatus.Visible = true;
                btnRefuse.Visible = false;
                btnAccept.Visible = false;
            }
        }


    }
    protected void btnSend_Command(object sender, CommandEventArgs e)
    {
        
    }
}
